package com.yinhe.music.yhmusic.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import com.apkfuns.logutils.LogUtils;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.application.AppCache;
import com.yinhe.music.yhmusic.constants.BasicConfig;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.model.Music;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 文件工具类
 * Created by wcy on 2016/1/3.
 */
public class FileUtils {
    private static final String MP3 = ".mp3";
    private static final String LRC = ".lrc";
    private static final String IMG = ".jpg";
    public static final String lrcRootPath = Environment.getExternalStorageDirectory().toString() + "/yinhe/Lyric/";
    public static final String imgRootPath = Environment.getExternalStorageDirectory().toString() + "/yinhe/image/";

    private static String getAppDir() {
        return Environment.getExternalStorageDirectory() + "/SnowMusic/";
    }

    public static String getLrcDir() {
        String dir = getAppDir() + "Lyric/";
        return mkdirs(dir);
    }


    public static String getSplashDir(Context context) {
        String dir = context.getFilesDir() + "/splash_background/";
        return mkdirs(dir);
    }

    public static String getRelativeMusicDir() {
        String dir = "yinheMuscic/Music/";
        return mkdirs(dir);
    }

    public static boolean writeContentFromUrl(String urlpath, String lrcPath, String code) {
        try {
            LogUtils.i("code:" + code + " path = " + lrcPath + " url Path = " + urlpath);
            if (code == null) {
                code = "utf-8";
            }
            URL url = new URL(urlpath);
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();

            HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                File file = new File(lrcRootPath);
                if (!file.exists()) {
                    file.mkdirs();
                }

                BufferedReader bf = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), code));
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(lrcPath), "utf-8")));
                char[] c = new char[1024];
                int len;
                while ((len = bf.read(c)) != -1) {
                    out.write(c, 0, len);
                }

                bf.close();
                out.close();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void saveImage(Bitmap bmp, String title, String artist) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "/yinhe/image/");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = title + "-" + artist + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getLrcPath(String name) {
        return lrcRootPath + name + ".lrc";
    }

    public static String getImagePath(String title, String artist) {
        return imgRootPath + title + "-" + artist + ".jpg";
    }


    /**
     * 获取歌词路径
     * 先从已下载文件夹中查找，如果不存在，则从歌曲文件所在文件夹查找
     */
    public static String getLrcFilePath(Music music) {
        String lrcFilePath = BasicConfig.getInstance().getLyricDir() + music.getFileName().replace(MP3, LRC);
        if (!new File(lrcFilePath).exists()) {
            lrcFilePath = music.getFilePath().replace(MP3, LRC);
        }
        return lrcFilePath;
    }

    private static String mkdirs(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return dir;
    }

    public static String getMp3FileName(String artist, String title) {
        return getFileName(artist, title) + MP3;
    }

    public static String getLrcFileName(String artist, String title) {
        return getFileName(artist, title) + LRC;
    }

    public static String getFileName(String artist, String title) {
        artist = stringFilter(artist);
        title = stringFilter(title);
        if (TextUtils.isEmpty(artist)) {
            artist = AppCache.getContext().getString(R.string.unknown);
        }
        if (TextUtils.isEmpty(title)) {
            title = AppCache.getContext().getString(R.string.unknown);
        }
        return artist + " - " + title;
    }

    public static String getArtistAndAlbum(String artist, String album) {
        if (TextUtils.isEmpty(artist) && TextUtils.isEmpty(album)) {
            return "";
        } else if (!TextUtils.isEmpty(artist) && TextUtils.isEmpty(album)) {
            return artist;
        } else if (TextUtils.isEmpty(artist) && !TextUtils.isEmpty(album)) {
            return album;
        } else {
            return artist + " - " + album;
        }
    }

    /**
     * 过滤特殊字符(\/:*?"<>|)
     */
    private static String stringFilter(String str) {
        if (str == null) {
            return null;
        }
        String regEx = "[\\/:*?\"<>|]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static float b2mb(int b) {
        String mb = String.format(Locale.getDefault(), "%.2f", (float) b / 1024 / 1024);
        return Float.valueOf(mb);
    }

    public static void saveLrcFile(String path, String content) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(path));
            bw.write(content);
            bw.flush();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Uri getImageUrl(String str) {
        try {
            int index = str.lastIndexOf("/");
            String head = str.substring(0, index + 1);
            String temp = str.substring(index + 1);
            String url = URLEncoder.encode(temp, "UTF-8");
            return Uri.parse(head + url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getImage(String str) {
        try {
            int index = str.lastIndexOf("/");
            String head = str.substring(0, index + 1);
            String temp = str.substring(index + 1);
            String url = URLEncoder.encode(temp, "UTF-8");
            return head + url;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getJpgUrl(String str) {
        String indexStr = "?";
        if (str.contains(indexStr)) {
            int index = str.lastIndexOf("?");
            MLog.debug("image", str.substring(0, index));
            return str.substring(0, index);
        } else {
            return str;
        }
    }


    public static String getCharacterAndNumber() {
        String rel;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
        Date curDate = new Date(System.currentTimeMillis());
        rel = formatter.format(curDate);
        return rel;
    }

    public static String getFileName() {
        return getCharacterAndNumber();
    }


}
